﻿using Dapper;
using Entity;
using IRepository;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace Repository
{
    public class TargetFormRepository : ITargetFormRepository, IDisposable
    {
        private readonly IDbConnection _dbConnection;
        private bool _disposed = false;

        public TargetFormRepository(IConfiguration configuration)
        {
            string connectionString = configuration.GetConnectionString("DefaultConnection");
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("数据库连接字符串 'DefaultConnection' 未配置");
            }
            _dbConnection = new SqlConnection(connectionString);
            _dbConnection.Open();
        }

        /// <summary>
        /// 获取所有可用的目标表单
        /// </summary>
        public List<TargetForm> GetAll()
        {
            // 数据库字段为TargetForm，对应实体类的TargetForm属性
            string sql = "SELECT TargetID, TargetForm FROM TargetFormTable WHERE IsActive = 1";
            try
            {
                return _dbConnection.Query<TargetForm>(sql).AsList();
            }
            catch (SqlException ex)
            {
                throw new Exception("查询目标表单列表失败", ex);
            }
        }

        /// <summary>
        /// 根据ID获取目标表单
        /// </summary>
        public TargetForm GetById(int targetId)
        {
            if (targetId <= 0)
                throw new ArgumentOutOfRangeException(nameof(targetId), "目标表单ID必须大于0");

            string sql = "SELECT TargetID, TargetForm FROM TargetFormTable WHERE TargetID = @TargetId AND IsActive = 1";
            try
            {
                return _dbConnection.QueryFirstOrDefault<TargetForm>(sql, new { TargetId = targetId });
            }
            catch (SqlException ex)
            {
                throw new Exception($"查询ID为{targetId}的目标表单失败", ex);
            }
        }

        /// <summary>
        /// 根据名称获取目标表单ID
        /// </summary>
        public int? GetTargetIdByName(string targetFormName)
        {
            if (string.IsNullOrWhiteSpace(targetFormName))
                return null;

            // 数据库字段为TargetForm
            string sql = "SELECT TargetID FROM TargetFormTable WHERE TargetForm = @TargetFormName AND IsActive = 1";
            try
            {
                return _dbConnection.QueryFirstOrDefault<int?>(sql, new { TargetFormName = targetFormName });
            }
            catch (SqlException ex)
            {
                throw new Exception($"根据名称获取目标表单ID失败: {targetFormName}", ex);
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing && _dbConnection != null && _dbConnection.State != ConnectionState.Closed)
                {
                    _dbConnection.Close();
                    _dbConnection.Dispose();
                }
                _disposed = true;
            }
        }

        ~TargetFormRepository()
        {
            Dispose(false);
        }
    }
}
